package org.example.filter;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import org.example.config.RedisCache;
import org.example.entity.UserLogin;
import org.example.util.CommonResult;
import org.example.util.JwtUtil;
import org.example.util.WebUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author: gx.wu
 * @create: 2023-05-09 23:21
 * @Description: 自定义token验证Filter，基于 BasicAuthenticationFilter
 */
@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    @Resource
    private RedisCache redisCache;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {

        //1、获取请求头携带的token
        String token = request.getHeader("Authorization");
        if(!StringUtils.hasText(token)){
            //不需要token的路由可以直接放行
            filterChain.doFilter(request,response);
            return;
        }
        token = token.replace("Bearer ", "");
        //2、解析出userId
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            //token超时或者非法
            CommonResult result = CommonResult.fail(null, "登录失效，请重新登录");
            WebUtils.renderString(response, JSON.toJSONString(result));//返回一个JSON数据，但是这个方法是void的，所以自定义了一个工具类，方便返回JSON
            return;
        }
        String userId = claims.getSubject();
        //3、从redis中获取用户信息
        UserLogin loginUser = redisCache.getCacheObject("login"+userId);
        if(Objects.isNull(loginUser)){
            CommonResult result = CommonResult.fail(null, "登录失效，请重新登录");
            WebUtils.renderString(response, JSON.toJSONString(result));
            return;
        }
        //4、如果能返回用户信息，存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(request,response); //放行

    }
}
